import React, {useEffect, useState} from "react";
import './App.css';
function App() {
    const [listening, setListening] = useState(false);
    const [data, setData] = useState([]);
    let eventSource = undefined;

    useEffect(() => {
        if (!listening) {
        // eslint-disable-next-line
        // 后端的服务地址
        eventSource = new window.EventSource("http://localhost:80/time");

        eventSource.onopen = (event) => {
            console.log("connection opened");
        };
        eventSource.onmessage = (event) => {
            console.log("result", event.data);
            setData((old) => [...old, event.data]);
        };
        eventSource.onerror = (event) => {
            console.log(event.target.readyState);
            if (event.target.readyState === EventSource.CLOSED) {
                console.log("eventsource closed (" + event.target.readyState + ")");
            }
            eventSource.close();
        };

        setListening(true);
        }
        return () => {
            eventSource.close();
            console.log("eventsource closed");
        };
    }, []);
    return (
        <div className="App">
            <header className="App-header">
                Received Data
                {data.map((d) => (
                <span key={d}>{d}</span>
                ))}
            </header>
        </div>
    );
}

export default App;
